package com.bsj.travel.filter;

import com.alibaba.fastjson.JSONObject;
import com.bsj.travel.config.properties.CaptchaProperties;
import com.bsj.travel.def.global.JsonResult;
import com.bsj.travel.exception.ApiException;
import com.bsj.travel.service.ValidateCodeService;
import com.bsj.travel.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author yinhao
 * @version 1.0
 * @description 验证码过滤器
 * @date 2023/10/18
 */
@Component
@Slf4j
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {

    private final static String[] DATE_URL = new String[] {"/auth/login", "/auth/register"};

    private static final String CODE = "code";
    private static final String UUID = "uuid";
    @Autowired
    private CaptchaProperties captchaProperties;
    @Autowired
    private ValidateCodeService validateCodeService;

    @Override
    public GatewayFilter apply(Object obj) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            //非登录/注册的请求或验证码关闭，不处理
            if (!StringUtils.containsAnyIgnoreCase(request.getURI().getPath(), DATE_URL) || !captchaProperties.getEnabled()) {
                return chain.filter(exchange);
            }
            String rspStr = resolveBodyFromRequest(request);
            JSONObject object = JSONObject.parseObject(rspStr);
            try {
                // TODO 进行验证码验证
                validateCodeService.checkCaptcha(object.getString(CODE), object.getString(UUID));
            } catch (ApiException e) {
//                log.error("ValidateCodeFilter error : {}", ExceptionUtil.getStackStr(e));
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), JsonResult.fail(e.getStatus()));
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
        //请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(dataBuffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
            DataBufferUtils.release(dataBuffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
